const { resolve } = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin')
const ESlintWebpackPlugin = require('eslint-webpack-plugin')

module.exports = {
  entry: ['./src/js/index.js', './src/index.html'],
  output: {
    filename: 'js/[name].[contenthash:10].js',
    path: resolve(__dirname, 'build')
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          {
            loader: 'postcss-loader',
            options: {
              postcssOptions: {
                plugins: [
                  'postcss-preset-env'
                ]
              }
            }
          }
        ]
      },
      {
        test: /\.less/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          {
            loader: 'postcss-loader',
            options: {
              postcssOptions: {
                plugins: [
                  'postcss-preset-env'
                ]
              }
            }
          },
          'less-loader'
        ]
      },
      {
        test: /\.html$/,
        loader: 'html-loader'
      },
      {
        test: /\.js$/,
        exclude: resolve(__dirname, 'node_modules'),
        loader: 'babel-loader',
        options: {
          presets: [
            '@babel-preset-env',
            {
              useBuiltIns: 'usage',
              corejs: {
                version: 3
              },
              targets: {
                chrome: '60',
                firefox: '60',
                safari: '17',
                ie: '9',
                edge: '10'
              }
            }
          ],
          cacheDirectory: true
        }
      },
      {
        test: /\.(png|jpg|gif)$/,
        type: 'asset',
        parser: {
          dataUrlCondition: {
            maxSize: 8 * 1024
          }
        },
        generator: {
          filename: 'img/[hash:10].[ext]'
        }
      },
      {
        test: /\.(woff2|eot|ttf)$/,
        type: 'asset/resource',
        generator: {
          filename: 'font/[hash:10].[ext]'
        }
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
      minify: {
        collapseWhitespace: true,
        removeComments: true
      }
    }),
    new MiniCssExtractPlugin({
      filename: 'css/[name].[contenthash:10].css'
    }),
    new OptimizeCssAssetsWebpackPlugin(),
    new ESlintWebpackPlugin({
      fix: true
    })
  ],
  mode: 'development',
  devServer: {
    static: resolve(__dirname, ' build'),
    port: 3000,
    compress: true,
    open: true
  },
  devtool: 'eval-source-map',
  optimization: {
    splitChunks: {
      chunks: 'all'
    }
  }
}
